# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

import hashlib
import http
import time

from scrapy import signals
import pymysql
from .settings import MYSQL_CONNECT, PROXIES, REDIS_CONNECT
import requests
from scrapy.http import response, HtmlResponse
from scrapy.http.request import Request
import random  # 代理IP的引用
import redis


class GlobalinternationTreaSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your singaporespiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class GlobalinternationTreaspiderDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your singaporespiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.
        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


# 基于redis的增量爬取
class UrlRedisFilter(object):
    redis_host = REDIS_CONNECT['REDIS_HOST']
    redis_port = REDIS_CONNECT['REDIS_PORT']
    redis_passwd = REDIS_CONNECT['REDIS_PASSWD']
    redis_db = REDIS_CONNECT['REDIS_DB']

    def __init__(self):
        self.pool = redis.ConnectionPool(host=self.redis_host, port=self.redis_port, password=self.redis_passwd,
                                         db=self.redis_db, decode_responses=True)

    # def process_request(self, request, spider):
    #     systemid = str(hashlib.md5(request.url.encode('utf-8')).hexdigest())
    #     rediscursor = redis.Redis(connection_pool=self.pool)
    #     try:
    #         right = rediscursor.sismember(REDIS_CONNECT['REDIS_KEY'], systemid)
    #     except:
    #         raise redis.RedisError
    #     if right:
    #         print('该网站已经被爬取')
    #         rediscursor.close()
    #         return HtmlResponse(url=request.url,body=None)
    #     else:
    #         print('该网站未被爬取')
    #         rediscursor.close()
    #         return None

    def process_spider_output(self, response, result, spider):
        for request in result:
            if isinstance(request, Request):
                systemid = str(hashlib.md5(request.url.encode('utf-8')).hexdigest())
                rediscursor = redis.Redis(connection_pool=self.pool)
                try:
                    right = rediscursor.sismember(REDIS_CONNECT['REDIS_KEY'], systemid)
                except:
                    raise redis.RedisError
                if right:
                    print('该网站已经被爬取')
                    rediscursor.close()
                    yield None
                else:
                    print('该网站未被爬取')
                    rediscursor.close()
                    yield request
            else:
                yield request


# 这是配置代理IP的函数
class ProxyMiddleware(object):

    def process_request(self, request, spider):
        print('进入代理IP函数成功')
        proxy = random.choice(PROXIES)
        request.meta['proxy'] = proxy


# 这是使用浏览器插件处理JS网页的函数
class GLobalLawWebdriverDownloaderMiddleware(object):

    def process_request(self, request, spider):
        weburls = ['http://asean.pkulaw.cn/List?categoryId=002&language=zh-CN',
                   ]
        spider_names = ['wipo_treaty', 'cnkispider']
        if request.url in weburls:
            driver = spider.driver  # 调用本地的谷歌浏览器
            driver.get(request.url)  # 请求页面，会打开一个浏览器窗口
            time.sleep(2)
            lurl = driver.page_source
            res = HtmlResponse(url=request.url, encoding='utf8', body=lurl, request=request)
            return res
        if spider.name in spider_names:
            driver = spider.driver  # 调用本地的谷歌浏览器
            driver.get(request.url)  # 请求页面，会打开一个浏览器窗口
            time.sleep(2)
            lurl = driver.page_source
            res = HtmlResponse(url=request.url, encoding='utf8', body=lurl, request=request)
            return res
        return None
